<!--顶部饼图组件-->
<template>
  <div class="pie-chart-wrapper" :style="wrapperStyle">
    <div ref="chartRef" class="pie-chart-canvas"></div>
  </div>

  <!-- 鼠标悬停时，由 tooltip 显示标题与分类数据 -->
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from "vue";
//导入echarts环形图
import * as echarts from "echarts";

const props = defineProps({
  title: { type: String, required: true },
  total: { type: Number, required: true },
  unit: { type: String, required: true },
  data: { type: Array, required: true },
  // 环形图颜色，可自定义，默认两段颜色
  colors: {
    type: Array,
    default: () => ["#000", "#E9F1FF"],
  },
  // 组件尺寸（正方形），默认 180px；传入 0 或负值时占满父容器
  size: { type: Number, default: 180 },
});

const chartRef = ref(null);
let chartInstance = null;
let resizeObserver = null;

const wrapperStyle = computed(() => {
  if (props.size && props.size > 0) {
    return { width: props.size + "px", height: props.size + "px" };
  }
  return { width: "100%", height: "100%" };
});

/**
 * 将数字格式化为中文千分位分隔符或万单位
 * 大于10000的数值转换为万单位（如133333转为13.3w）
 * 若转换失败则原样返回字符串
 * @param {number|string} n - 待格式化的数字或字符串
 * @returns {string} 格式化后的字符串
 */
const formatNumber = (n) => {
  try {
    const num = Number(n);
    if (num >= 10000) {
      const wan = num / 10000;
      // 保留一位小数，去除末尾的0
      return (Math.round(wan * 10) / 10).toString().replace(/\.0$/, "") + "w";
    }
    return num.toLocaleString("zh-CN");
  } catch (e) {
    return String(n);
  }
};
/**
 * 环形图数据配置
 */
const renderChart = () => {
  if (!chartRef.value) return;
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }

  const option = {
    color: props.colors,
    tooltip: {
      trigger: "item",
      // 示例：数据统计<br/>空闲中10个
      formatter: (p) => `${props.title}<br/>${p.name}：${p.value}${props.unit}`,
    },
    series: [
      {
        name: props.title,
        type: "pie",
        radius: ["68%", "88%"],
        avoidLabelOverlap: true,
        label: { show: false },
        labelLine: { show: false },
        itemStyle: {
          borderWidth: 0,
        },
        // 鼠标悬停放大效果
        emphasis: {
          scale: true,
          scaleSize: 4,
        },
        data: props.data,
      },
    ],
    // 中心静态文案（标题 + 总数 + 单位）
    graphic: [
      {
        type: "text",
        left: "center",
        top: "40%",
        style: {
          text: props.title,
          fill: "#666",
          fontSize: 12,
          fontWeight: 500,
        },
      },
      {
        type: "group",
        left: "center",
        top: "55%",
        children: [
          {
            type: "text",
            style: {
              text: formatNumber(props.total),
              fill: "#1f1f1f",
              fontSize: 22,
              fontWeight: 700,
              x: 0,
              y: 0,
            },
          },
          {
            type: "text",
            style: {
              text: props.unit,
              fill: "#ECECEC",
              fontSize: 12,
              fontWeight: 400,
              x: formatNumber(props.total).length * 11 + 6, // 根据数值长度调整单位位置
              y: 6, // 向下偏移，形成右下角效果
            },
          },
        ],
      },
    ],
  };

  chartInstance.setOption(option);
};

onMounted(() => {
  renderChart();
  // 跟随容器大小变化响应式调整
  if (chartRef.value && "ResizeObserver" in window) {
    resizeObserver = new ResizeObserver(() => {
      chartInstance && chartInstance.resize();
    });
    resizeObserver.observe(chartRef.value);
  } else {
    window.addEventListener(
      "resize",
      () => chartInstance && chartInstance.resize()
    );
  }
});

onUnmounted(() => {
  if (resizeObserver) {
    try {
      resizeObserver.disconnect();
    } catch (e) {}
    resizeObserver = null;
  }
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});

// 数据变化时更新图表
watch(
  () => [props.data, props.total, props.title, props.unit, props.colors],
  () => {
    renderChart();
  }
);
</script>

<style scoped lang="scss">
.pie-chart-wrapper {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.pie-chart-canvas {
  width: 100%;
  height: 100%;
}
</style>
